/*
 * @Author: wwssaabb
 * @Date: 2021-07-10 10:47:36
 * @LastEditTime: 2021-07-14 17:16:10
 * @FilePath: \demo\blog_demo\middleware\loginGuard.js
 */


//登录拦截
const {getUser}=require('../route/user')

const allowPage=['/admin/login','/blog/','/blog','/favicon.ico','/blog/article?_id=']  //未登录允许访问的页面

const guard=async (ctx,next)=>{
  const _user=getUser()
  let url=ctx.request.url
  if(!_user) ctx.session.username=null
  console.log('登录拦截')
  console.log('url:',url)

  if(ctx.request.method==='POST'){
    await next()
  }else if(ctx.request.method==='GET'){
    if(allowPage.includes(url)||url.includes(allowPage[allowPage.length-1])){
      await next()
    }else{
      if(!_user||!ctx.session.username){
        if(!allowPage.includes(url)){
          ctx.redirect('/admin/login')
          await next()
        }else{
          await next()
        }
      }else{
        if(_user.role=='admin'){
          await next()
        }else{
          if(url.includes('admin')&&!allowPage.includes(url)){
            ctx.redirect('/blog/')
            await next()
          }else{
            console.log('ddddd')
            await next()
          }
        }
      }
    }
  }
  
  
  
}

module.exports=guard